#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
from logging.handlers import RotatingFileHandler

def initLog(logfile, level=2, verbose=False):
    '''
    Default log level: INFO (2)
    verbose: - default [False], print log. msg. in std.out
    '''
    logLevel = logging.INFO
    if level == 0:
        logLevel = logging.NOTSET
    elif level == 1:
        logLevel = logging.DEBUG
    elif level == 2:
        logLevel = logging.INFO
    elif level == 3:
        logLevel = logging.WARNING
    elif level == 4:
        logLevel = logging.ERROR
    elif level == 5:
        logLevel = logging.CRITICAL

    logger = logging.getLogger()
    if logfile:
        fhanlder = logging.FileHandler(logfile)
        logger.setLevel(logLevel)
        formatter = logging.Formatter('[%(asctime)s] %(levelname)8s %(name)s %(threadName)s %(lineno)d "%(message)s"', \
                                      '%Y-%m-%d %a %H:%M:%S')
        fhanlder.setFormatter(formatter)
        logger.addHandler(fhanlder)


    if verbose:
        console = logging.StreamHandler()
        console.setLevel(logLevel)    # always debug mode to screen
        formatter = logging.Formatter('%(name)s %(levelname)-8s %(threadName)s %(lineno)d %(message)s')
        console.setFormatter(formatter)
        logger.addHandler(console)

    return logger

if __name__ == '__main__':
    logger = initLog('log.txt', 2, True)
    
    logger.debug("debug %s", "1")
    logger.info("info %s", "2")
    logger.warning("warning %s", "3")
    logger.error("error %s", "4")
    logger.critical("critical %s", "5")
    